<template>
  <div>
    <el-dialog title="编辑图片" :visible.sync="isShowEditPicture" width="70%" append-to-body center
               @close="closeEditPicture">
      <div style="display: flex;align-items: center;margin: 10px 0">
        <el-button type="success" size="small" @click="handleSubmit()">确认已翻译</el-button>
      </div>
      <el-tabs v-model="tabsValue" type="border-card" @tab-click="tabsClick">
        <el-tab-pane v-for="(item,index) in tabsList" :key="index" :label="item.label" :name="item.name">
          <el-table v-loading="loading" :data="imgDetailList" border stripe :key="isUpdateTable">
            <!--            <el-table-column type="selection" width="40" align="center"></el-table-column>-->
            <el-table-column label="图片" align="center">
              <template slot-scope="scope">
                <image-upload isLimitsize :atlasType="tabsValue" :isShowSize="true"
                              v-model="scope.row" :changeSize="true" :isShowTip="false" :limit="1"
                              :tabValue="tabsValue"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleEdit(scope.row, scope.$index)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 编辑图片 -->
    <el-dialog
      title="编辑图片"
      :visible.sync="isEditPicture"
      width="1500px">
      <PictureEditor ref="pictureRef" :key="new Date().getTime()" :data="pictureData"
                     :onCompleted="onCompleted"/>
    </el-dialog>
  </div>
</template>

<script>
import {pictureEditor} from "@/api/picture/picture";
import {dataURLtoFile} from "@/utils/dataURLtoFile";
import uuid from "@/utils/uuid";
import PictureEditor from "@/components/PictureEditor/index.vue";
import {bucketUpload} from "@/utils/alioss";
import {confirmTranslate} from "@/api/picture/optimizeTask";

export default {
  name: "editPicture",
  components: {
    PictureEditor,
  },
  props: {
    productId: {},
    imgList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      isShowEditPicture: true,
      isEditPicture: false,
      imgDetailList: [],//展示图片列表
      editImgList: this.imgList,//编辑图片列表
      pictureData: "",
      tabsList: [
        {
          name: '0',
          label: '轮播图'
        }, {
          name: '1',
          label: '详情图'
        }, {
          name: '2',
          label: '营销图'
        }, {
          name: '3',
          label: '白底图'
        }
      ],//选项卡列表
      tabsValue: 0,//选项卡选中的标签
      loading: false,//表格加载
      isUpdateTable: false,
      rotationImg: "",
      detailImg: "",
      marketingImg: "",
      whiteImg: "",
      editIndex: "",
      editImgData: ""
    }
  },
  created() {
    console.log('imgDetailList', this.imgDetailList)
    // this.getImgDetailList()
    window.addEventListener('message', this.receiveMessage, true);
    this.tabsClick()
    this.getTranslateImg()
  },
  methods: {
    // 获取已翻译的图片
    getTranslateImg() {
      this.rotationImg = this.editImgList[0][0].pics//轮播图
      this.detailImg = this.editImgList[1][0].pics//详情图
      this.marketingImg = this.editImgList[2][0].pics//营销图
      this.whiteImg = this.editImgList[3][0].pics//白底图
    },
    handleSubmit() {
      this.$confirm('是否确认已翻译？', '提示').then(res => {
        let rotationImgList = [], detailImgList = [];
        for (let i = 0; i < this.rotationImg.length; i++) {
          if (this.rotationImg[i].indexOf('https://') != -1) {
            rotationImgList.push(this.rotationImg[i].replace('https://file.pbb2c.com/', ''))
          }
          if (this.rotationImg[i].indexOf('http://') != -1) {
            rotationImgList.push(this.rotationImg[i].replace('http://file.pbb2c.com/', ''))
          }
        }
        this.rotationImg = rotationImgList
        console.log('imageURLs', this.rotationImg)
        for (let i = 0; i < this.detailImg.length; i++) {
          if (this.detailImg[i].indexOf('https://') != -1) {
            detailImgList.push(this.detailImg[i].replace('https://file.pbb2c.com/', ''))
          }
          if (this.detailImg[i].indexOf('http://') != -1) {
            detailImgList.push(this.detailImg[i].replace('http://file.pbb2c.com/', ''))
          }
        }
        this.detailImg = detailImgList
        let data = {
          "id": this.productId,
          "imageURLs": this.rotationImg.toString(),
          "white": this.whiteImg.toString(),
          "detailImg": this.detailImg.toString(),
          "marketing": this.marketingImg,
          "editStatus": 3
        }
        console.log('data', data)
        confirmTranslate(data).then(res => {
          this.$message.success(res.msg)
          this.closeEditPicture()
        })
      })
    },
    // 切换选项卡
    tabsClick(tab, event) {
      this.selectValue = "" //把下拉框的值置为空
      this.isDisSelect = true
      console.log('this.editImgList', this.editImgList)
      this.imgDetailList = this.editImgList[this.tabsValue][0].pics
      console.log('this.imgDetailList', this.imgDetailList)
    },
    // 编辑图片
    handleEdit(row, index) {
      console.log('row', index)
      this.loading = true;
      this.editIndex = index
      const pics = (row || '').split(',').filter(item => !!item);
      let url = "";
      if (pics.length > 0) {
        url = pics[0]
      } else {
        url = row
      }
      if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) url = this.$store.getters.domain + url
      pictureEditor({url: url}).then(res => {
        if (res.code === 200) {
          this.loading = false;
          this.isEditPicture = true;
          this.pictureData = res.data;
          this.$nextTick(() => {
            this.$refs.pictureRef.init('1');
          })
        }
      })
    },
    onCompleted(data) {
      const op = dataURLtoFile(data[0], uuid() + '.jpg');
      this.handleUpload(op);
    },
    // 上传
    handleUpload(op) {
      console.log("handleUpload", op)
      let bucketName = 'temp-product' // 桶名
      let dir = `images`
      bucketUpload(
        op,
        res => {
          let temp = {
            name: res.attachment,
            url: res.aliyunAddress,
            code: res.code
          }
          console.log('res', res)
          this.choosePic = temp.name;
          this.isEditPicture = false;
          if (this.tabsValue == 0) {
            this.rotationImg[this.editIndex] = res.aliyunAddress
            this.imgDetailList = this.rotationImg
            console.log(' this.rotationImg', this.rotationImg)
          } else if (this.tabsValue == 1) {
            this.detailImg[this.editIndex] = res.aliyunAddress
            this.imgDetailList = this.detailImg
          } else if (this.tabsValue == 2) {
            this.marketingImg[this.editIndex] = res.aliyunAddress
            this.imgDetailList = this.marketingImg
          } else {
            this.whiteImg[this.editIndex] = res.aliyunAddress
            this.imgDetailList = this.whiteImg
          }
          // this.$refs.pictureRef.remove()
        },
        err => {
        },
        bucketName,
        dir
      )
      // this.$refs.pictureRef.$destroy() //销毁编辑图片组件
    },
    receiveMessage(event) {
      if (event.data && !event.data.type) {
        const postData = JSON.parse(event.data);
        const {type, data} = postData;
        console.log('type', type, data)
        switch (type) {
          case 'base64':
            this.onCompleted(data);
            return false;
          case 'psd':
            this.onChange(data);
            return false;
          case 'autoHeight':
            const iframe = document.getElementById('editor-Iframe');
            iframe.style.height = data.editorHeight + 'px';
            return false;
          default:
            return false;
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseTableId = selection.map(item => item.imgId)
      // this.collectProductIds = selection.map(item => item.collectProductId)
      this.chooseIds = selection.map(item => item.id)
      this.optimizePics = selection.map(item => item.optimizePic)
      if (this.chooseTableId && this.chooseTableId.length > 0) {
        this.isDisSelect = false
      } else {
        this.isDisSelect = true
        this.selectValue = ""
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 关闭编辑图片
    closeEditPicture() {
      this.$emit('closeEditPicture', false)

    },
  }
}
</script>

<style scoped>

</style>
